package com.c8a.validation.utils.valid;

import com.c8a.validation.annotation.ValidCollection;
import com.c8a.validation.exception.CollectionValidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

/**
 *
 * 集合校验
 *
 * @Author C8A
 * @Date 2022-04-24 18:10
 * @Email 1912327276@qq.com
 */


public class AnnValidCollection implements ConstraintValidator<ValidCollection, Collection> {

    @Autowired
    private Validator validator;

    Class<?>[] grouping;

    boolean quickFail;


    @Override
    public void initialize(ValidCollection validList) {
        grouping = validList.grouping();
        quickFail = validList.quickFail();

    }

    @Override
    public boolean isValid(Collection list, ConstraintValidatorContext context) {
        int index = 0;
        HashMap<Integer, Set<ConstraintViolation<Object>>> validMap = new HashMap<>(list.size());
        for (Object o : list) {
            Set<ConstraintViolation<Object>> validSet = validator.validate(o, grouping);
            if (!CollectionUtils.isEmpty(validSet)) {
                validMap.put(index, validSet);
            }
            ++index;
        }

        if (quickFail && !CollectionUtils.isEmpty(validMap)) {
            throw new CollectionValidException(validMap);
        }

        return true;
    }
}
